/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controlador;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.sql.DataSource;
import modelo.Caja;
import persistencia.CajaBean;

@WebListener
public class StartSession implements HttpSessionListener {

    @Resource(name = "jdbc/HOLAJDBC")
    private DataSource ds;

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        System.out.print("A las " + getTime() + "  se creo la sesion con ID: "
                + session.getId() + " MaxInactiveInterval="
                + session.getMaxInactiveInterval());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        System.out.println("A las " + getTime() + " se destruyo la sesion con ID: "
                + session.getId());

        Date fecha = new Date();
        Caja caja = (Caja) session.getAttribute("CAJA");
        if (caja != null) {
            Connection conexion = null;
            try {
                conexion = ds.getConnection();
            } catch (SQLException ex) {
                Logger.getLogger(StartSession.class.getName()).log(Level.SEVERE, null, ex);
            }
            caja.setFechaCierre(fecha);
            CajaBean bean = new CajaBean(conexion);
            bean.finalizar(caja);
        }
    }

    private String getTime() {
        return new Date(System.currentTimeMillis()).toString();
    }
}
